//
//  HSYShopManageViewController.m
//  HSY
//
//  Created by 陈浩 on 2017/4/10.
//  Copyright © 2017年 金开门. All rights reserved.
//

#import "HSYShopManageViewController.h"
#import "HSYScanQRCodeViewController.h"
#import "HSYShopListModel.h"
#import "HSYShopManageCell.h"
#import "BQActivityView.h"
#import "HSYGetShopListRequest.h"
#import "HSYBindQrcodeRequest.h"
#import "HSYShopInfoViewController.h"
#import "HSYNewShopViewController.h"

static NSString *const cellReuseIdentifier = @"cellReuseIdentifier";

@interface HSYShopManageViewController ()

@property(nonatomic,strong)HSYShopListModel *model;

@end

@implementation HSYShopManageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self.tableView registerNib:[UINib nibWithNibName:@"HSYShopManageCell" bundle:nil] forCellReuseIdentifier:cellReuseIdentifier];
    
    self.tableView.tableFooterView = [UIView new];
    if (self.isSelectShop) {
        [self.titleButton setTitle:@"选择店铺" forState:UIControlStateNormal];
    }else{
        [self.titleButton setTitle:@"店铺管理" forState:UIControlStateNormal];
        [self.rightAreaRBtn setTitle:@"新增店铺" forState:UIControlStateNormal];
        self.rightAreaRBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
        
        [self.rightAreaRBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.right.mas_equalTo(self.rightArea.mas_right).offset(-5);
            make.centerY.mas_equalTo(self.rightArea.mas_centerY);
            make.height.mas_equalTo(@40);
            make.width.mas_equalTo(@76);
        }];

    }
    
    [self getShopList];

}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}


- (BOOL)hsy_allowPullUp{
    return NO;
}

- (BOOL)hsy_allowPullDown{
    return NO;
}

-(void)handleNavigationAction:(HSYNavigationActionType)actionType{
    if (HSYNavActionRightAreaRight == actionType) {
        [self newShop];
    }
    
    if (HSYNavActionLeftAreaLeft == actionType) {
        [self handleGoBackEvent:nil];
    }
}



-(void)getShopList{
    HSYGetShopListRequest *task = [[HSYGetShopListRequest alloc] init];
    task.uid = [HSYUserCenter instatce].appAuUser.uid;
    
    __weak typeof(self)weakSelf = self;
    [BQActivityView showActiviTy];

    [HSYNetworkManager POST:task success:^(HSYResponse *response) {
        [BQActivityView hideActiviTy];

        if (response.resultCode == HSY_REQUEST_CODE_SUCCESS) {
            HSYShopListModel *model = [HSYShopListModel mj_objectWithKeyValues:response.encryptDataResult];
            weakSelf.model = model;
            
            [weakSelf.tableView reloadData];
        }else{
            [weakSelf showMessage:response.resultMessage];
        }
        
    } failure:^(NSError *error) {
        [BQActivityView hideActiviTy];
        
        if (error.code != NSURLErrorCancelled) {
            [weakSelf showMessage:@"请求超时"];
        }
    }];
}

#pragma mark - 新增店铺 -

- (void)newShop{
    HSYNewShopViewController *vc = [[HSYNewShopViewController alloc] init];
    
    __weak typeof(self) wSelf = self;
    vc.completeBlock = ^{
        [wSelf getShopList];
    };
    
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)showShopDetail:(HSYShopInfoModel *)shopModel{
    HSYShopInfoViewController *vc = [[HSYShopInfoViewController alloc] init];
    vc.shopModel = shopModel;
    
    [self.navigationController pushViewController:vc animated:YES];

}

#pragma mark - 绑定二维码 -

- (void)scanQRCodeWithShopModel:(HSYShopInfoModel *)model{
    HSYScanQRCodeViewController *vc = [[HSYScanQRCodeViewController alloc] init];
    __weak typeof(self)weakSelf = self;
    
    vc.scanResultBlock = ^(NSDictionary * info){
        if (info[@"code"]) {
            [weakSelf bindQRcode:info[@"code"] shopid:model.shopID];
        }else{
            [weakSelf showMessage:info[@"resultString"]];
        }
    };
    
    HSYBaseNavigationController *nav = [HSYBaseNavigationController navigtationControllerWithRootViewController:vc];
    
    [self presentViewController:nav animated:YES completion:nil];
}


/**
 绑定二维码
 @param code code
 @param shopid 商铺id
 */
-(void)bindQRcode:(NSString *)code shopid:(NSString *) shopid{
    HSYBindQrcodeRequest *task = [[HSYBindQrcodeRequest alloc] init];
    task.code = code;
    task.shopId = shopid;
    task.uid = [HSYUserCenter instatce].appAuUser.uid;
    
    __weak typeof(self)weakSelf = self;
    [BQActivityView showActiviTy];

    [HSYNetworkManager POST:task success:^(HSYResponse *response) {
        [BQActivityView hideActiviTy];
        [weakSelf showMessage:response.resultMessage];

        if (response.resultCode == HSY_REQUEST_CODE_SUCCESS) {
            [weakSelf getShopList];
        }
        
    } failure:^(NSError *error) {
        [BQActivityView hideActiviTy];
        
        if (error.code != NSURLErrorCancelled) {
            [weakSelf showMessage:@"请求超时"];
        }
    }];
    
}


#pragma mark UITableViewDelegate,UITableViewDataSource

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.model.shopList.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 72.0;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    HSYShopInfoModel *shopModel = self.model.shopList[indexPath.row];
    
    HSYShopManageCell *cell = [tableView dequeueReusableCellWithIdentifier:cellReuseIdentifier forIndexPath:indexPath];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    cell.bindingQCBtn.enabled = shopModel.countQR > 0 ? NO : YES;
    
    if (shopModel.countQR > 0) {
        [cell.bindingQCBtn setTitle:@"已绑定二维码" forState:UIControlStateNormal];
    }else{
        [cell.bindingQCBtn setTitle:@"绑定二维码" forState:UIControlStateNormal];
    }


    if (self.isSelectShop) { //如果是选择店铺， 则隐藏此按钮
        cell.bindingQCBtn.hidden = YES;
    }

    __weak typeof(self)weakSelf = self;
    cell.bindingQCBlock = ^{
        [weakSelf scanQRCodeWithShopModel:shopModel];
    };
    
//    if (shopModel.type == 1) {
//        cell.shortNameLabel.text = @"主店";
//    }else{
//        cell.shortNameLabel.text = shopModel.shortName;
//    }
//    
    cell.shopNameLabel.text = shopModel.shortName.length ? shopModel.shortName : shopModel.name;
//    cell.qrCountLabel.text = [NSString stringWithFormat:@"二维码个数：%ld", (long)shopModel.countQR];
//    cell.employeeCountLabel.text = [NSString stringWithFormat:@"店员个数：%ld", (long)shopModel.countEmployee];
    cell.shopkeeperLabel.hidden = shopModel.parentID ? YES : NO;
    
    return cell;
    
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    HSYShopInfoModel *shopModel = self.model.shopList[indexPath.row];

    if (self.selectShopBlock) {
        self.selectShopBlock(shopModel, self);
        
        [self.navigationController popViewControllerAnimated:YES];
    }else{
        [self showShopDetail:shopModel];
    }

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
